package com.smartlight.godlight;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.smartlight.godlight.adapter.GridImageAdapter;
import com.smartlight.godlight.listener.OnItemClickListener;
import com.smartlight.godlight.model.Buddha;
import com.smartlight.godlight.model.Fruit;
import com.smartlight.godlight.model.Light;

import java.util.ArrayList;
import java.util.List;

import kotlin.collections.ArrayDeque;

public class SelectGod extends AppCompatActivity {

    private final String TAG = "SelectGod";
    private List<Light> lightList = new ArrayList<>();
    private RecyclerView recyclerView;
    private  SwipeRefreshLayout swipeRefreshLayout;
    private  GridImageAdapter adapter;


    @Override
    protected void  onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selectgod);

        // actionbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // 获取ActionBar对象（实际上是Toolbar）并设置属性
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true); // 显示返回箭头
            actionBar.setHomeAsUpIndicator(R.drawable.arrow_yellow); // 设置返回图标
            actionBar.setTitle("请选择未被点亮的佛灯"); // 设置标题文字
//            toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.dark_yellow));
        }

        Intent intent = getIntent();
        Buddha buddha = intent.getParcelableExtra("buddha");
        Log.d(TAG, "传过来的独享----" + buddha.getId() + " :" + buddha.getName() + ":" + buddha.getImg());
        int startNum = buddha.getStart_num();
        int endNum = buddha.getEnd_num();

        // 获取佛灯列表
        getBuddhaLightList(startNum, endNum);

        // 刷新UI
        recyclerView = findViewById(R.id.recyclerView);
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 10)); // 设置网格布局管理器。
        adapter = new GridImageAdapter(this, lightList, 10); // 初始化适配器。
        recyclerView.setAdapter(adapter); // 设置适配器。
        swipeRefreshLayout.setOnRefreshListener(() -> {
            // 设置下拉刷新监听器。这里可以调用加载数据的逻辑。例如：
            Log.d(TAG, "下拉刷新更多。。。。。");
            Toast.makeText(this, "下拉刷新更多", Toast.LENGTH_LONG).show();
            loadData();
        });

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Light light = lightList.get(position);
                Log.d(TAG, "点击了" + position + " : 数据是: " + light.toString());

                if (light.getStatus() == 1){
                    new MaterialAlertDialogBuilder(SelectGod.this)
                            .setTitle("温馨提示")
                            .setMessage("该佛灯已被点亮，请您选择其他未被点亮的！")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    // 点击确定按钮后的操作
                                }
                            })
                            .setNegativeButton("取消", null)
                            .show();
                }
                else {
                    Intent intent2 = new Intent();
                    intent2.putExtra("buddha_light_no", light.getName());
                    setResult(RESULT_OK, intent2);
                    finish();
                }
            }
        });

        // 监听上拉刷新
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition();
                int totalItemCount = layoutManager.getItemCount();
                if (lastVisibleItem >= totalItemCount - 1 && dy > 0) {
                    Toast.makeText(SelectGod.this, "滑动到底部", Toast.LENGTH_LONG).show();
                    // 判断是否滚动到底部，并且是向上滚动（dy > 0）触发的滚动事件，避免误判为下拉刷新时的滚动到底部事件
                    loadMoreData(); // 执行加载更多数据的操作
                }
            }
        });
    }

    private void getBuddhaLightList(int startNum, int endNum) {
        // 调用贵兴的接口匹配佛灯列表，并初始化
        // add code here
        for (int i = 0; i < 50; i ++) {
            int resourceId = (i % 2 == 1) ? R.drawable.buddha_light : R.drawable.buddha_grey;
            int status = (i % 2 == 1) ? 1 : 0;
            Light buddha = new Light("" + i, resourceId, status);
            lightList.add(buddha);
        }
    }

    private void loadMoreData() {
        initData();
        adapter.notifyDataSetChanged(); // 通知适配器数据已改变，UI将更新显示新数据
        adapter.setFooterViewVisible(true);
    }

    private void loadData() {
        adapter.notifyDataSetChanged(); // 通知适配器数据已改变，UI将更新显示新数据
        swipeRefreshLayout.setRefreshing(false); // 停止刷新动画
        adapter.setFooterViewVisible(true);
    }

    private void initData() {
        for (int i = 0; i < 50; i ++) {
            int resourceId = (i % 2 == 1) ? R.drawable.buddha_light : R.drawable.buddha_grey;
            int status = (i % 2 == 1) ? 1 : 0;
            Light buddha = new Light("" + i, resourceId, status);
            lightList.add(buddha);
        }
    }

}
